package com.siyoumi.controller;


import com.siyoumi.component.http.InputDataInterface;
import com.siyoumi.component.http.XHttpContext;
import lombok.NonNull;
import lombok.SneakyThrows;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class BaseController
        implements InputDataInterface {
    @Override
    public String input(@NonNull String k, String def) {
        return XHttpContext.input(k, def);
    }

    public HttpServletRequest getRequest() {
        return XHttpContext.getHttpServletRequest();
    }

    public HttpServletResponse getResponse() {
        return XHttpContext.getHttpServletResponse();
    }

    /**
     * 导出txt
     *
     * @param fileName
     * @param txt
     */
    @SneakyThrows
    public void exportTxt(String fileName, String txt) {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(txt.getBytes(StandardCharsets.UTF_8));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
            }
        }
    }
}
